#!/usr/bin/perl

## Henrik Linde 2014-03-27 ##

use DBI;

my $dbname = 'links.db';
my $tablename = 'linkList';
my $db;

sub connectDB {	$db = DBI->connect("dbi:SQLite:$dbname", "", "",{RaiseError => 1, AutoCommit => 1});}

sub createDB  {	
	$db->do("CREATE TABLE $tablename (id INTEGER PRIMARY KEY, linkURL TEXT, linkTEXT TEXT)");
}

sub populateDB{	
	$db->do("INSERT INTO $tablename VALUES (NULL,'$1', '$2')");
}

sub html_head{
    print "Content-type:text/html\r\n\r\n";
    print "<html>";
    print "<head>";
    print "<title>Länkar som kan vara bra att ha</title>";
    print "</head>";
}

sub html_form{
    print "<FORM action='/cgi-bin/link_post.cgi' method='POST'>";
    print "URL: <input type='text' name='URL'>  <br>";
    print "Name: <input type='text' name='Name'>";
    print "<input type='submit' value='Submit'>";
    print "</FORM>";
}

sub insertFromDB{	
	my $all = $db->selectall_arrayref("SELECT * FROM $tablename");
	foreach my $row (@$all) {
		my ($id, $linkURL, $linkTEXT) = @$row;
		print "<br><a href='${linkURL}'>${linkTEXT}</a>\n";
	}
}
 
sub make_html{
    html_head();
    print "<body>";
    print "<h2>Bra att spara...</h2>";
    html_form();
    insertFromDB();
    print "</body>";
    print "</html>\n";
}

sub main{
	unless (-e $dbname){
	
	connectDB();
		createDB();
	}
	else {
		connectDB();
	}

	local ($buffer, @pairs, $pair, $name, $value, %FORM);
	# Read in text
	$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
	if ($ENV{'REQUEST_METHOD'} eq "POST")
	{
	    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	}else {
	    $buffer = $ENV{'QUERY_STRING'};
	}
	# Split information into name/value pairs
	@pairs = split(/&/, $buffer);

	foreach $pair (@pairs){
	    ($name, $value) = split(/=/, $pair);
	    $value =~ tr/+/ /;
	    $value =~ s/%(..)/pack("C", hex($1))/eg;
	    $FORM{$name} = $value;
	    $URL_TEXT = $FORM{URL};
	    $Info_TEXT  = $FORM{Name};


	}
	$db->do("INSERT INTO ${tablename} VALUES (NULL,'${URL_TEXT}','${Info_TEXT}')");
	#populateDB($FORM{URL},$FORM{Name});
	


	make_html();
}

main();
